<?
require_once("ericdingle/model/BaseProvider.php");
require_once("ericdingle/model/link/LinkEntity.php");

class LinkProvider extends BaseProvider {
	public static function getInstance() {
		return parent::getInstance(__CLASS__);
	}
	
	// CRUD
	
	public function create($link) {
		$linkID = $this->dataInterface_->executeNonQuery(sprintf(
			"INSERT INTO Link (LinkID, Label, Link) " .
			"VALUES (NULL, '%s', '%s')",
			$this->dataInterface_->sanitize($label->getLabel()),
			$this->dataInterface_->sanitize($label->getLink())
		));
		
		$label->setLinkID($linkID);
	}
	
	public function read($link = null, $orderBy = null, $limit = null) {
		if (!$orderBy) $orderBy = "L.Label ASC";
		
		$result = $this->dataInterface_->executeQuery(
			"SELECT L.LinkID, L.Label, L.Link " .
			"FROM Link L " .
			($link ? "WHERE " . $this->getContraints($link) . " " : "") .
			"ORDER BY $orderBy"
		);
		
		if (!$result) {
			die($this->dataInterface_->getError());
		}
		
		$links = array();
		while ($row = $this->dataInterface_->getNextRow($result)) {
			array_push($links, $this->loadEntity($row));
		}
		
		return $links;
	}
	
	public function update($link) {
		$this->dataInterface_->executeNonQuery(sprintf(
			"UPDATE Link " .
			"SET Label = '%s', Link = '%s' " .
			"WHERE LabelID = %d",
			$this->dataInterface_->sanitize($link->getLabel()),
			$this->dataInterface_->sanitize($link->getLink()),
			$link->getLinkID()
		));	
	}
	
	public function delete($link) {
		$this->dataInterface_->executeNonQuery(sprintf(
			"DELETE FROM Link " .
			"WHERE LinkID = %d",
			$link->getLinkID()
		));
	}
	
	// Helpers
	
	private function getConstraints($link) {
		$constraints = array();
		if ($linkID = $link->getLinkID()) {
			array_push($constraints, sprintf("L.LinkID = %d", $linkID));
		}
		return implode(" AND ", $constraints);
	}
	
	private function loadEntity($row) {
		return new LinkEntity(
			$row["LinkID"],
			$row["Label"],
			$row["Link"]
		);
	}
}
?>
